package com.bls.productmall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bls.productmall.entity.Order;
import com.bls.productmall.entity.User;
import com.bls.productmall.enums.OrderStatus;
import com.bls.productmall.mapper.OrderMapper;
import com.bls.productmall.mapper.UserMapper;
import com.bls.productmall.service.OrderService;
import com.bls.productmall.util.ExportExcel;
import com.bls.productmall.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
    *  分页查询订单
    * */
    @Override
    public R getOrderPage(int current, int size) {
        List<Order> orderList = orderMapper.selectList(null);
        int total = orderList.size();
        int start = (current-1) * size;
        List<Order> orderList1 = orderMapper.getOrderPage(start, size);
        for (Order order : orderList1) {
            order.setUserName(userMapper.selectById(order.getUserId()).getName());
        }
        return R.ok().setMessage("分页查询").setTotal(total).data("orderList", orderList1);
    }

    /**
    * 根据用户名来查询用户id,再进行分页查询
    * */
    @Override
    public R getOrderByUserName(String userName, int current, int size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userName);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return R.error().setMessage("用户不存在");
        }
        int userId = user.getId();
        // 获取id匹配的订单总数
        QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userId);
        List<Order> orderList = orderMapper.selectList(queryWrapper1);
        int total = orderList.size();
        // 根据id来进行订单分页查询
        int start = (current-1) * size;
        List<Order> orderList1 = orderMapper.getOrderByUserId(userId, start, size);
        for (Order order : orderList1) {
            order.setUserName(userMapper.selectById(order.getUserId()).getName());
        }
        return R.ok().setMessage("根据用户名来分页查询订单").setTotal(total).data("orderList", orderList1);
    }

    /**
    * 根据订单id来删除订单
    * */
    @Override
    public int deleteOrderByOrderId(int orderId) {
        return orderMapper.deleteById(orderId);
    }

    /*
    * 根据订单号获取订单信息
    * */
    @Override
    public Order getOrderByOrderNo(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = baseMapper.selectOne(queryWrapper);
        return order;
    }

    /**
     * 根据订单号更新订单状态
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        log.info("更新订单状态 ===> {}", orderStatus.getType());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = new Order();
        order.setOrderStatus(orderStatus.getType());
        baseMapper.update(order, queryWrapper);
    }

    /**
     * 根据订单号获取订单状态
     */
    @Override
    public String getOrderStatus(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = baseMapper.selectOne(queryWrapper);
        if(order == null){
            return null;
        }
        return order.getOrderStatus();
    }

    /**
    *  导出数据为excel
    */
    @Override
    public void exportExcel(OutputStream out, String excelTitle) throws IOException {
        // 定义列标 就是一个Excel的每一个字段标题
        String[] rowsName = new String[]{"订单id", "用户", "订单号", "产品名称", "价格/￥", "订单状态", "更新时间"};
        // 创建导出数据集合 后续会将dataList中的数据写到Excel
        List<Object[]> dataList = new ArrayList<>();
        // 从数据库查询用户列表（需要的可以自行添加参数）
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        List<Order> orderList = orderMapper.selectList(queryWrapper);
        Order order = null;
        // 将列表信息封装到一个Object数组
        // 我这里封装Object数组 是为了方便后续代码复用,不会将对象类型写死
        for (int i=0; i<orderList.size(); i++){
            //将数据库查到的每条数据 循环封装到Object[]
            order=orderList.get(i);
            order.setUserName(userMapper.selectById(order.getUserId()).getName());
            Object[] objs = new Object[]{order.getId(),order.getUserName(),order.getOrderNo(),order.getTitle(), order.getTotalFee()*0.01, order.getOrderStatus(),order.getUpdateTime()};
            //将转换好的数据 存入dataList
            dataList.add(objs);
        }
        // 创建ExportExcel工具类对象 通过构造方法赋值
        ExportExcel ex = new ExportExcel(excelTitle, rowsName, dataList);
        try {
            // 调用生成Excel的方法,将数据通过输出流写出
            ex.export(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

}
